package com.pj.xfxh.project.serviceimpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pj.xfxh.domain.RoleContent;
import com.pj.xfxh.project.entity.TopicMessage;
import com.pj.xfxh.project.mapper.TopicMessageMapper;
import com.pj.xfxh.project.service.TopicMessageService;
import org.springframework.stereotype.Service;

import javax.management.Query;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TopicMessageServiceImpl extends ServiceImpl<TopicMessageMapper, TopicMessage> implements TopicMessageService {

    @Override
    public List<RoleContent> getMessagesByUserId(Long userId,Long topicId,Long platformId) {
        // 通过userId查询历史对话信息

        QueryWrapper<TopicMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("topic_id",topicId);
        queryWrapper.eq("user_id",userId);
        queryWrapper.eq("platform_id",platformId);
        List<TopicMessage> list = this.list(queryWrapper);

        List<RoleContent> roleContentList = new ArrayList<>();
        list.forEach(t->{
            RoleContent roleContent = new RoleContent();
            roleContent.setContent(t.getMessageText());
            roleContent.setRole(t.getDialogueRole());
            roleContentList.add(roleContent);
        });

        return roleContentList;
    }

    @Override
    public List<TopicMessage> saveMessages(Long userId, Long topicId, Long platformId, List<RoleContent> roleContents) {
        // 将历史对话信息保存到数据库
        List<TopicMessage> messages = convertToTopicMessages(userId, topicId, platformId, roleContents);
        saveBatch(messages);

        List<Long> collect = messages.stream()
                .map(TopicMessage::getMessageId) // 使用.map将TopicMessage对象转换为它们的id
                .collect(Collectors.toList());// 将结果收集到一个新的List中

        List<TopicMessage> topicMessageList = listByIds(collect);

        return topicMessageList;
    }

    private List<TopicMessage> convertToTopicMessages(Long userId, Long topicId, Long platformId, List<RoleContent> roleContents) {
        // 将RoleContent转换为TopicMessage
        List<TopicMessage> messages = new ArrayList<>();
        for (RoleContent roleContent : roleContents) {
            TopicMessage message = new TopicMessage();
            message.setUserId(userId);
            message.setTopicId(topicId);
            message.setPlatformId(platformId);
            message.setDialogueRole(roleContent.getRole());
            message.setMessageText(roleContent.getContent());
            // 可以根据实际情况设置其他字段
            messages.add(message);
        }
        return messages;
    }

}
